package com.zhihu_lvliangi_android.option.zhengwu.fragment;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhihu_lvliangi_android.R;
import com.zhihu_lvliangi_android.domain.JsonPageModel;
import com.zhihu_lvliangi_android.domain.ZhengwuColumnItem;
import com.zhihu_lvliangi_android.option.parent.ParentFragment;
import com.zhihu_lvliangi_android.service.DataFormat;
import com.zhihu_lvliangi_android.service.MobileApplication;
import com.zhihu_lvliangi_android.service.TaskID;
import com.zhihu_lvliangi_android.util.Constant;
import com.zhihu_lvliangi_android.util.RequestURL;
import com.zhihu_lvliangi_android.util.Utils;



public class Catergory_Theme_Fragment extends ParentFragment implements OnClickListener {
	
	private List<String> mTitles;
	private List<ZhengwuColumnItem> mPersonalColumnItems = new ArrayList<ZhengwuColumnItem>();//面向个人
	private List<ZhengwuColumnItem> mEnterpriseColumnItems = new ArrayList<ZhengwuColumnItem>();//面向\企业
	private TextView mDepartmentCategoryTextView;
	private Category_Theme_items items;;
	private int currentPos = -1;
	private Gson gson = new Gson();
	private  View mParentView;
	/**
	 * columnItems为空则发起网络请求
	 * @param columnItems
	 * @param list 
	 * @return
	 */
	public static Catergory_Theme_Fragment newInstance(){
		Catergory_Theme_Fragment department = new Catergory_Theme_Fragment();
		return department;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
//		setUseMain_scrollview(false);
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		System.out.println("onActivityCreated");
		super.onActivityCreated(savedInstanceState);
		setContentView(R.layout.fragment_zhengwu_theme);
		if (mPersonalColumnItems.size()>0 || mEnterpriseColumnItems.size()>0) {
			setContentShown(true);
		}else {
			setContentShown(false);
		}
		
		initView();
	}
		

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_progress;
	}

	@Override
	protected void setupViews(View parentView) {
		
		
	}

	private void initView() {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		mParentView = getContentView();
		LinearLayout container =(LinearLayout) mParentView.findViewById(R.id.container);

		for (int i = 0; i < mTitles.size(); i++) {
			View view = inflater.inflate(R.layout.fragment_theme_item, null);
			view.setTag(i);
			view.setOnClickListener(this);
			mDepartmentCategoryTextView= (TextView) view.findViewById(R.id.department_item_title);
			mDepartmentCategoryTextView.setText(mTitles.get(i));
			view.findViewWithTag(Catergory_Theme_Fragment.this.getClass().getSimpleName()).setId(Utils.generateViewId());
			container.addView(view, i);
		}
	}

	@Override
	protected void initialized(Bundle savedInstanceState) {
		System.out.println("super ==initialized");
		mTitles = Arrays.asList(getResources().getStringArray(R.array.zhengwu_catergory_Theme_Type));
		
		//从缓存中取数据,无数据传递null TODO
		
		String	cache_1= MobileApplication.cacheUtils.getAsString(Constant.CACHE_ZHENGWU_OBJ_1);
		String cache_2 = MobileApplication.cacheUtils.getAsString(Constant.CACHE_ZHENGWU_OBJ_2);
		if (TextUtils.isEmpty(cache_1) ||TextUtils.isEmpty(cache_2) ) {
			Log.e(MobileApplication.TAG, "==========需要请求网络数据==========");
			MobileApplication.getInstance().clientTask.executeGet(TaskID.TASK_APP_ZHENGWU_COLUM_INIT_1
					, DataFormat.STRING, RequestURL.getGuideTypesForTheme(), this);
			MobileApplication.getInstance().clientTask.executeGet(TaskID.TASK_APP_ZHENGWU_COLUM_INIT_2
					, DataFormat.STRING, RequestURL.getGuideTypesForEnterprise(), this);
			MobileApplication.getInstance().clientTask.cancelLoadingView();
			return ;
		}
		mPersonalColumnItems = parseData(cache_1).getResult().getRows();
		mEnterpriseColumnItems =  parseData(cache_2).getResult().getRows();
	}

	private JsonPageModel<ZhengwuColumnItem> parseData(String cache) {
		try {
				return gson.fromJson(cache,new TypeToken<JsonPageModel<ZhengwuColumnItem>>(){}.getType() );
		} catch (Exception e) {
				return null;
		}
	}

	@Override
	public void threadTask() {
		
		//请求所有项目内容 
				if (mPersonalColumnItems.size() == 0 ||mEnterpriseColumnItems.size() == 0) {
					return;
				}
				if (TextUtils.isEmpty(MobileApplication.cacheUtils.getAsString(mPersonalColumnItems.get(0).getGuide_type_id()))) {
					for (ZhengwuColumnItem item : mPersonalColumnItems) {
						
						MobileApplication.getInstance().clientTask.executeGet(TaskID.TASK_APP_ZHENGWU_GUIDE_ITEM, DataFormat.STRING, 
								RequestURL.getGuideItemByTypeID(item.getGuide_type_id()), new MyListener(item.getGuide_type_id()));
					}
					
					for (ZhengwuColumnItem item : mEnterpriseColumnItems) {
						MobileApplication.getInstance().clientTask.executeGet(TaskID.TASK_APP_ZHENGWU_GUIDE_ITEM, DataFormat.STRING, 
								RequestURL.getGuideItemByTypeID(item.getGuide_type_id()), new MyListener(item.getGuide_type_id()));
					}
				}
	}

	
	class MyListener implements Listener<Object>{

		private String mID;
		public MyListener(String id){
			
			this.mID = id;
		}
		@Override
		public void onResponse(Object response, Enum<?> reqId) {
			MobileApplication.cacheUtils.put(mID, response.toString());
		}
		
	}
	
	@Override
	public void onClick(View v) {
		try {
			int pos = Integer.parseInt(v.getTag().toString());
			changeItemForCategory(pos,v);
		} catch (NumberFormatException e) {
			//TODO 处理v.getid()
			throw new RuntimeException(e);
		}
	}
	
	
	
	@Override
	public void onResponse(Object response, Enum<?> reqId) {
		super.onResponse(response, reqId);
		switch ((TaskID)reqId) {
		case TASK_APP_ZHENGWU_COLUM_INIT_1:
			MobileApplication.cacheUtils.put(Constant.CACHE_ZHENGWU_OBJ_1, response.toString());
			mPersonalColumnItems = parseData(response.toString()).getResult().getRows();
			break;
		case TASK_APP_ZHENGWU_COLUM_INIT_2:
			MobileApplication.cacheUtils.put(Constant.CACHE_ZHENGWU_OBJ_2, response.toString());
			mEnterpriseColumnItems = parseData(response.toString()).getResult().getRows();
			
			break;
		default:
			break;
		}
		setContentShown(true);//显示界面
	}
	
	
	

	private void changeItemForCategory(final int pos, final View v) {
			if (currentPos ==pos ) {
				Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_min_arrow_reverse);
				v.findViewById(R.id.mini_arrow).startAnimation(anim);
				anim.setAnimationListener(new AnimationListener() {
					
					@Override
					public void onAnimationStart(Animation animation) {
						
					}
					
					@Override
					public void onAnimationRepeat(Animation animation) {
						
					}
					
					@Override
					public void onAnimationEnd(Animation animation) {
						if (items==null) {
							return;
						}
						getActivity().getSupportFragmentManager().beginTransaction().
						setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).
						remove(items).
						commit();
						currentPos = -1;
					}
				});
			}else {
				Animation anim =AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_min_arrow);
				v.findViewById(R.id.mini_arrow).startAnimation(anim);
				anim.setAnimationListener(new AnimationListener() {
					
					@Override
					public void onAnimationStart(Animation animation) {
						
					}
					
					@Override
					public void onAnimationRepeat(Animation animation) {
						
					}
					
					@Override
					public void onAnimationEnd(Animation animation) {
						int id  = v.findViewWithTag(Catergory_Theme_Fragment.this.getClass().getSimpleName()).getId();
						items = Category_Theme_items.newInstance(pos == 0? mPersonalColumnItems:mEnterpriseColumnItems);
						getActivity().getSupportFragmentManager().beginTransaction().
						//R.anim.push_left_in,R.anim.push_left_out,R.anim.push_right_in,R.anim.push_right_out
						setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).
						replace(id, items).
						commit();
						currentPos = pos;
					}
				});
				
			}
	}

	
	
	
	

	

}
